package hip.util;

import java.io.*;

public class ObjectEncoder {


    public static Object toObjectss(byte[] common) throws ClassNotFoundException, IOException {
        // 二进制序列化为对象
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(common);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return objectInputStream.readObject();
    }

    public static byte[] toBytess(Object obj) throws IOException {
        byte[] body;
        if (obj instanceof String) {
            body = ((String) obj).getBytes();
        } else {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            try {
                objectOutputStream.writeObject(obj);
                body = byteArrayOutputStream.toByteArray();
            } finally {
                objectOutputStream.flush();
                objectOutputStream.close();
                byteArrayOutputStream.flush();
                byteArrayOutputStream.close();
            }
        }
        return body;
    }

    /**
     * 对象转字节
     */
    public byte[] toBytes(Object obj) throws IOException {
        return toBytess(obj);
    }
}
